﻿using System.Windows;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Scheduler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.IO.IsolatedStorage;


namespace myAgent
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private static volatile bool _classInitialized;

        public IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
        // Pour la modification de la tile
        ShellTileSchedule SampleTileSchedule = new ShellTileSchedule();
        bool TileScheduleRunning = false;
        //Pour le code
        public List<Article2> newArticle2;
        public Dictionary<String, Article2> myTuple;


        /// <remarks>
        /// Le constructeur ScheduledAgent initialise le gestionnaire UnhandledException
        /// </remarks>
        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                // S'abonner au gestionnaire d'exceptions prises en charge
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// Code à exécuter sur les exceptions non gérées
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Une exception non gérée s'est produite ; arrêt dans le débogueur
                System.Diagnostics.Debugger.Break();
            }
        }

        /// <summary>
        /// Agent qui exécute une tâche planifiée
        /// </summary>
        /// <param name="task">
        /// La tâche appelée
        /// </param>
        /// <remarks>
        /// Cette méthode est appelée lorsqu'une tâche périodique ou  resource intensive est appelée
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            //TODO: ajoutez du code pour exécuter votre tâche en arrière-plan
            //TODO: Add code to perform your task in background



            Test();


            //string[] Message = new string[2];
            //Message = task.Description.Split('§');
            // Launch a toast to show that the agent is running.
            // The toast will not be shown if the foreground application is running.
            //ShellToast toast = new ShellToast();
            //toast.Title = Message[0];
            //toast.Content = Message[1];
            //toast.Show();




            ShellTile TileToFind = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("TileID=2"));
            //test si le Tile a ete cree
             if (TileToFind == null)
             {
                 StandardTileData NewTileData;
                 if (newArticle2 == null || !(newArticle2.Count > 0))
                 {
                     NewTileData = new StandardTileData
                     {

                         BackgroundImage = null,
                         Title = "Gift Idea",
                         BackTitle = "",
                         BackContent = "Gift Idea",
                         Count = 0
                     };
                  
                 }
                 else
                 {
                     NewTileData = new StandardTileData
                     {

                         BackgroundImage = null,
                         Title = "Gift Idea",
                         BackTitle = "Gift Idea",
                         BackContent = newArticle2.First<Article2>().UserName,
                         Count = newArticle2.Count,
                         //BackBackgroundImage = new Uri(newArticle2.First<Article2>().Image, UriKind.Absolute)
                     };
                 }
                 //ShellTile.Create(new Uri("/ScheduledAgent.cs", UriKind.Relative), NewTileData);
             }


            //Permet de relancer l'alerte toutes les minutes
            ScheduledActionService.LaunchForTest(task.Name, System.TimeSpan.FromSeconds(20));
            

            // Call NotifyComplete to let the system know the agent is done working.
            NotifyComplete();
        }

        private void Test()
        {

            //ICI appel action la fonction requete webService
            //Article2 art1 = new Article2("Chocolat","www.google.fr","chocolat au lait", "" ,"10","Michel Knoertzer","Michel.Knoertzer@gmail.fr");

            List<Article2> Article2 = new List<Article2>();
            Article2.Add(new Article2 { Name = "Chocolat", Url = "www.google.fr", Description = "chocolat au lait", Image = "http://i.msdn.microsoft.com/dynimg/IC505313.png", Prix = "10", UserName = "Michel Knoertzer", UrlUser = "Michel.Knoertzer@gmail.fr" });


            //Article2.Add(art1);
            SaveArticle2s(Article2);
            CallNotification();

        }

        private void SaveArticle2s(List<Article2> Article2)
        {

            newArticle2 = new List<Article2>();
            myTuple = new Dictionary<String, Article2>();
            foreach (Dictionary<String, Article2> dico in settings.Values)
            {
                myTuple = dico;
            }
            if (myTuple == null) //(!settings.TryGetValue("Articles2List", out myTuple))
            {
                myTuple = new Dictionary<String, Article2>();
                foreach (Article2 art in Article2)
                {
                        myTuple.Add(art.Name + art.UrlUser + art.UserName, art);
                        newArticle2.Add(art);
                }

            }
            else
            {
                foreach (Article2 art in Article2)
                {
                    if (!(myTuple.ContainsKey(art.Name + art.UrlUser + art.UserName)))
                    {
                        myTuple.Add(art.Name + art.UrlUser + art.UserName, art);
                        newArticle2.Add(art);
                    }
                }
            }
            //settings.Remove("Article2sList");
            if (newArticle2.Count > 0)
            {
                settings.Add("Article2sList", myTuple);
                settings.Save();
            }

        }

        private void CallNotification()
        {
            if (newArticle2.Count > 0)
            {

                foreach (Article2 art in newArticle2)
                {
                    //StartPeriodicAgent(art);
                    ShellToast toast = new ShellToast();
                    toast.Title = art.UserName;
                    toast.Content = art.Name;
                    toast.Show();
                }

            }

        }
    }
}